// Copyright  2012 Petr TALLA. [petr.talla@gmail.com]
// This file is free software; you can redistribute it and/or modify it
// under the terms of the GNU Lesser General Public License
// as published by the Free Software Foundation; either
// version 2 of the License, or (at your option) any later version.
//
// This file is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY;  without even the implied warranty
// of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
// See the GNU Lesser General Public License for more details.
// [http://www.gnu.org/copyleft/lesser.html]
//=============================================================================

package tc.common.utility;

import java.awt.geom.Point2D;

//import tc.map.GrTiledMap;

public class TcDisplayXY {
	public enum CoordSys { WORLD, PAPPER, VIEW,	DEVICE };

	public TcDisplayTransf view;
	public CoordSys        coordSys;
	public Point2D.Double         xy;
	
	public TcDisplayXY (Point2D.Double xy, TcDisplayTransf view, CoordSys coordSys) {
		this.xy = new Point2D.Double(xy.x, xy.y);
		this.view = view;
		this.coordSys = coordSys; 
	}
	
	public void transform(CoordSys coordSysNew) {
		if (coordSys == coordSysNew) return;
		
		switch (coordSys) {
		case WORLD:
			doWORLDtoPAPPER();
			break;
		case PAPPER:
			if ( coordSysNew == CoordSys.WORLD) doPAPPERtoWORLD();
			else doPAPPERtoVIEW();
			break;
		case VIEW:
			if ( coordSysNew == CoordSys.DEVICE) doVIEWtoDEVICE();
			else doVIEWtoPAPPER();
			break;
		case DEVICE:
			doDEVICEtoVIEW();
			break;
		}
		
		transform(coordSysNew);
	}
	
	void doDEVICEtoVIEW() {
		assert coordSys == CoordSys.DEVICE;
		xy.x /= view.ppm*view.width/2.0;
		xy.y /= view.ppm*view.height/2.0;
		xy.x -= 1.0;
		xy.y -= 1.0;
		xy.y *= -1.0;
		coordSys = CoordSys.VIEW;
	}
	
	void doVIEWtoDEVICE() {
		assert coordSys == CoordSys.VIEW;
		xy.y *= -1.0;
		xy.x += 1.0;
		xy.y += 1.0;
		xy.x *= view.ppm*view.width/2.0;
		xy.y *= view.ppm*view.height/2.0;

		coordSys = CoordSys.DEVICE;
	}
	
	void doVIEWtoPAPPER() {
		assert coordSys == CoordSys.VIEW;
		xy.x *= view.width/2.0;
		xy.y *= view.height/2.0;
		xy.x += view.center.x*view.scaleX;
		xy.y += view.center.y*view.scaleY;
		coordSys = CoordSys.PAPPER;
	}
	
	void doPAPPERtoVIEW() {
		assert coordSys == CoordSys.PAPPER;
		xy.x -= view.center.x*view.scaleX;
		xy.y -= view.center.y*view.scaleY;
		xy.x /= view.width/2.0;
		xy.y /= view.height/2.0;
		coordSys = CoordSys.VIEW;
	}
	
	private void doWORLDtoPAPPER() {
		assert coordSys == CoordSys.WORLD;
		xy.x *= view.scaleX;
		xy.y *= view.scaleY;
		coordSys = CoordSys.PAPPER;
	}
	
	private void doPAPPERtoWORLD() {
		assert coordSys == CoordSys.PAPPER;
		xy.x /= view.scaleX;
		xy.y /= view.scaleY;
		coordSys = CoordSys.WORLD;
	}
}
